<?php

namespace App\Http\Controllers\PrizePayment;

use App\App\Services\AlipayService;
use App\Http\Controllers\Controller;
use App\Models\Prize\PrizeService;
use App\Models\PrizePayment\PrizePaymentService;
use App\Models\PrizeRecord\PrizeRecordService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;

class AlipayController extends Controller
{
    /**
     * 即时到帐
     * @param Request $request
     * @param AlipayService $alipayService
     * @param PrizePaymentService $prizePaymentService
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function pay(Request $request, AlipayService $alipayService, PrizePaymentService $prizePaymentService)
    {
        $orderId = $request->query->get('order_id');
        $paymentInfo = $prizePaymentService->find(['order_id' => $orderId]);
        if (!empty($paymentInfo) && !$paymentInfo->isUnpaid()) {
            return view('web.prize.alipayPay', ['message' => '订单不能提交']);
        }
        $paymentInfo->commited();
        $alipayUrl = $alipayService->getDirectPayUrl($paymentInfo);
        // 跳转到支付页面。
        Log::debug('支付宝发起支付:' . $alipayUrl);
        return view('web.prizePayment.alipayPay', ['url' => $alipayUrl, 'orderId' => $orderId]);
    }

    /**
     * 异步通知
     * 30天后支付结束只需返回success
     *
     * @param Request $request
     * @param PrizePaymentService $prizePaymentService
     *
     * @return string
     */
    public function webNotify(Request $request, PrizePaymentService $prizePaymentService, PrizeService $prizeService)
    {
        if (isset($_GET['url'])) {
            unset($_GET['url']);
        } elseif (isset($_POST['url'])) {
            unset($_POST['url']);
        }
        // 验证请求。
        if (!app('alipay.web')->verify()) {
            Log::notice('Alipay notify post data verification fail.', [
                'data' => $request->instance()->getContent(),
            ]);

            return 'fail';
        }
        Log::debug('alipay notify:' . Input::get('trade_status'));
        // 判断通知类型。
        switch (Input::get('trade_status')) {
            case 'TRADE_CLOSED':
                $order = $prizePaymentService->find(['order_id' => Input::get('out_trade_no')]);
                if ($order && $order->isCommit()) {
                    $order->failed();
                    Log::debug('支付关闭:' . Input::get('out_trade_no'));
                }
                break;
            case 'TRADE_SUCCESS':
            case 'TRADE_FINISHED':
                // TODO: 支付成功，取得订单号进行其它相关操作。
                Log::debug('Alipay notify post data verification success.', [
                    'out_trade_no' => Input::get('out_trade_no'),
                    'trade_no' => Input::get('trade_no'),
                ]);
                $order = $prizePaymentService->find(['order_id' => Input::get('out_trade_no')]);
                if ($order && $order->isCommit()) {
                    $prize = $order->prize;
                    if ($prize && !$prize->isValid()) {
                        if ($prize->setIsValid()) {
                            $order->paid();
                        }
                    }
                }
                break;
        }

        return 'success';
    }

    /**
     * 同步通知(已停用)
     * 支付完成，从支付宝跳转回来
     *
     * @param Request $request
     * @param PrizeService $prizeService
     * @param PrizePaymentService $prizePaymentService
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function webReturn(Request $request, PrizeService $prizeService, PrizePaymentService $prizePaymentService)
    {
        if (isset($_GET['url'])) {
            unset($_GET['url']);
        } elseif (isset($_POST['url'])) {
            unset($_POST['url']);
        }
        // 验证请求。
        if (!app('alipay.web')->verify()) {
            Log::notice('Alipay return query data verification fail.', [
                'data' => $request->getQueryString(),
            ]);

            return redirect()->to('/web/prize/create');
        }

        Log::info(Input::get('trade_status'));
        // 判断通知类型。
        switch (Input::get('trade_status')) {
            case 'TRADE_SUCCESS':
            case 'TRADE_FINISHED':
                // TODO: 支付成功，取得订单号进行其它相关操作。
                Log::debug('Alipay notify get data verification success.', [
                    'out_trade_no' => Input::get('out_trade_no'),
                    'trade_no' => Input::get('trade_no'),
                ]);
                $paymentInfo = $prizePaymentService->find(['order_id' => Input::get('out_trade_no')]);
                if ($paymentInfo && $paymentInfo->isCommit()) {
                    $prize = $paymentInfo->prize;
                    if ($prize && !$prize->isValid()) {
                        if ($prize->setIsValid()) {
                            $paymentInfo->paid();
                        }
                    }
                }
                break;
        }
        return view('web.prizePayment.alipayPay');
    }
}
